<template>
  <div class="anchors">
    <div class="anchors-list">
      <div
        v-for="(d, i) in anchorsList"
        :key="i"
        :class="['anchors-item', activeIndex === i ? 'is--active' : '']"
        @click="d.scrollIntoView({ behavior: 'smooth' }),activeIndex = i"
      >
        <div class="anchors-item__text">
          <div class="anchors-item__span">{{ d.innerText }}</div>
        </div>
        <div class="anchors-item__icon">
          <svg-icon :icon-class="d.getAttribute('data-icon') || ''" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { on, off } from '@/utils/dom'
import { onMounted } from 'vue'
const props = defineProps({
    props: { type: Object, default: () => ({}) },
    id: { type: [String, Number], default: 'anchors' },
    classes: { type: String, default: '.v-anchor' },
    scrollId: { type: String, default: 'v-page' }
})
const scrollNode = ref(null)
const scrollNodeY = ref(null)
const parentNode = ref(null)
const anchorsList = ref([])
const activeIndex = ref(0)

onMounted(()=>{
  nextTick(()=>{
      const scrollNode = document.getElementById(props.scrollId)
      scrollNode.value = scrollNode
      scrollNodeY.value = scrollNode.getBoundingClientRect().y - 1
      parentNode.value = document.getElementById(props.id)
      on(scrollNode.value, 'scroll', handleScroll)
      update()
  })
})
const handleScroll = ()=>{
  activeIndex.value = anchorsList.value.findIndex((d) => d.getBoundingClientRect().y > scrollNodeY.value)
}
const update = ()=>{
  nextTick(()=>{
        if (!parentNode.value) return
        anchorsList.value = Array.from(parentNode.value.querySelectorAll(classes.value))
        handleScroll()
  })
}
</script>

<style lang="scss" scoped>
.anchors{
  position: fixed;
  z-index: 1000;
  right: 17px;
  top: 50%;
  transform: translateY(-50%);
  width: 30px;
  padding: 10px 0;
  background-color: #f1f1f1;
  transition: .2s;
  overflow: hidden;
  box-shadow: 0 1px 10px rgba($color: #000000, $alpha: .2);
  &:hover{
    width: 130px;
    .anchors-list{
      z-index: 1;
    }
  }
  &-list{
    position: relative;
  }
  &-item{
    position: relative;
    height: 36px;
    line-height: 36px;
    background-color: #f1f1f1;
    cursor: pointer;
    &:hover, &.is--active{
      background-color: #ccc;
      .anchors-item__icon{
        background-color: #ccc;
      }
    }
    &__text{
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      height: 36px;
      line-height: 36px;
      padding-left: 10px;
      z-index: 0;
    }
    &__icon{
      position: absolute;
      right: 0;
      top: 0;
      width: 30px;
      height: 36px;
      padding: 0 6px;
      font-size: 16px;
      z-index: 1;
      background-color: #f1f1f1;
    }
  }
}
</style>